package calao.storage.bdb;

import com.sleepycat.je.DatabaseEntry;

class KeyRangeCursor
extends TableCursor
{

	DatabaseEntry minKey;
	DatabaseEntry maxKey;

	KeyRangeCursor(TableDatabase tdb) 
	{
		super(tdb);
	}
	
	void setMinKey(DatabaseEntry key)
	{
		this.minKey = key;
	}
	
	void setMaxKey(DatabaseEntry key)
	{
		this.maxKey = key;
	}

	@Override
	public boolean nextBdbHit() 
	{
		if (bdbCursor.hitCount==0) {
			if (minKey!=null) {
				if (!bdbCursor.getSearchKeyRange(minKey)) return false; 
			}
			else if (!bdbCursor.getFirst()) return false;
		}
		else if (!bdbCursor.getNext()) return false;
		if (maxKey!=null) {
			return compare(bdbCursor.getSearchedKey(), maxKey, maxKey.getSize())<=0;
		}
		else return true;
	}
	
	static int compare(DatabaseEntry key1, DatabaseEntry key2, int length)
	{
		byte[] data1 = key1.getData();
		byte[] data2 = key2.getData();
		for (int i=0; i<length; i++) {
			if (i==key1.getSize()) return -1;
			if (i==key2.getSize()) return 1;
			int b1 = data1[i];
			int b2 = data2[i];
			if (b1<0) b1 += 256;
			if (b2<0) b2 += 256;
			if (b1<b2) return -1;
			if (b1>b2) return 1;
		}
		return 0;
	}

	@Override
	String getTypeName()
	{
		return "key range";
	}

}
